<?php
if(!defined("YUEXUAN_REAL_ROOT_PATH")){
	exit("Access Denied.");
}

class mysqlException extends Exception {
	// pass
}

class ext_mysql {

	var $version = '';
	var $querynum = 0;
	var $link = null;

	function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE, $dbcharset2 = '') {

		$func = empty ( $pconnect ) ? 'mysql_connect' : 'mysql_pconnect';
		if (! $this->link =$func ( $dbhost, $dbuser, $dbpw, 1 )) {
			mysql_query("SET NAMES 'utf8'");
			$halt && $this->halt ( 'Can not connect to MySQL server' );
		} else {
			if ($this->version () > '4.1') {
				global $charset, $dbcharset;
				$dbcharset = $dbcharset2 ? $dbcharset2 : $dbcharset;
				$dbcharset = ! $dbcharset && in_array ( strtolower ( $charset ), array ('gbk', 'big5', 'utf8' ) ) ? str_replace ( '-', '', $charset ) : $dbcharset;
				$serverset = $dbcharset ? 'character_set_connection=' . $dbcharset . ', character_set_results=' . $dbcharset . ', character_set_client=binary' : '';
				$serverset .= $this->version () > '5.0.1' ? ((empty ( $serverset ) ? '' : ',') . 'sql_mode=\'\'') : '';
				$serverset && mysql_query ( "SET $serverset", $this->link );
			}
			$dbname && mysql_select_db ( $dbname, $this->link );
		}

	}

	function select_db($dbname) {
		return mysql_select_db ( $dbname, $this->link );
	}

	function fetch_array($query, $result_type = MYSQL_ASSOC) {
		return mysql_fetch_array ( $query, $result_type );
	}

	function fetch_first($sql) {
		return $this->fetch_array ( $this->query ( $sql ) );
	}

	function result_first($sql) {
		return $this->result ( $this->query ( $sql ), 0 );
	}

	function query($sql, $type = '') {
		$sql = str_replace('#tablePre#', MYSQL_TABLE_PRE, $sql);
        $query = mysql_query ( $sql, $this->link );
		//$query = mysql_unbuffered_query ( $sql, $this->link );
        if (mysql_errno()) {
        	$error = "MySQL error ".mysql_errno().": ".mysql_error()." When executing:$sql";
        	echo $error;
        	throw new mysqlException($error);
        }
		return $query;
		global $debug, $yuexuan_starttime, $sqldebug, $sqlspenttimes;
		// TODO 记录sql运行时间

		$func = $type == 'UNBUFFERED' && function_exists ( 'mysql_unbuffered_query' ) ? 'mysql_unbuffered_query' : 'mysql_query';
		if (! ($query = $func ( $sql, $this->link ))) {
			if (in_array ( $this->errno (), array (2006, 2013 ) ) && substr ( $type, 0, 5 ) != 'RETRY') {
				$this->close ();
				// TODO 重连
				$this->connect ( $dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset );
				$this->query ( $sql, 'RETRY' . $type );
			} elseif ($type != 'SILENT' && substr ( $type, 5 ) != 'SILENT') {
				$this->halt ( 'MySQL Query Error', $sql );
			}
		}

		$this->querynum ++;
		return $query;
	}

	function affected_rows() {
		return mysql_affected_rows ( $this->link );
	}

	function error() {
		return (($this->link) ? mysql_error ( $this->link ) : mysql_error ());
	}

	function errno() {
		return intval ( ($this->link) ? mysql_errno ( $this->link ) : mysql_errno () );
	}

	function result($query, $row = 0) {
		$query = mysql_result ( $query, $row );
		return $query;
	}

	function num_rows($query) {
		$query = mysql_num_rows ( $query );
		return $query;
	}

	function num_fields($query) {
		return mysql_num_fields ( $query );
	}

	function free_result($query) {
		return mysql_free_result ( $query );
	}

	function insert_id() {
		return ($id = mysql_insert_id ( $this->link )) >= 0 ? $id : $this->result ( $this->query ( "SELECT last_insert_id()" ), 0 );
	}

	function fetch_row($query) {
		$query = mysql_fetch_row ( $query );
		return $query;
	}

	function fetch_fields($query) {
		return mysql_fetch_field ( $query );
	}

	function version() {
		if (empty ( $this->version )) {
			$this->version = mysql_get_server_info ( $this->link );
		}
		return $this->version;
	}

	//whc
	function getRows($sql) {
		$query = $this->query ( $sql );
		while ( $row = $this->fetch_array ( $query ) ) {
			//$db->close();
			$rows [] = $row;
		}
		if (!isset ( $rows )) {
			 $rows=array();
		}

		return $rows;
	}
	//whc
	function getRow($sql) {
		//$query=$this->query($sql);
		return $this->fetch_first ( $sql );
	}

	//whc
	function getOne($sql) {
		$result = $this->fetch_first ( $sql );
		if ($result) {
			return $result [key ( $result )];
		} else {
			return false;
		}

	}

	//whc
	function getCols($sql) {
		$rows = $this->getRows ( $sql );
		if (count ( $rows ) > 0) {
			$key = key ( $rows [0] );
			$i = 0;
			foreach ( $rows as $row ) {
				$result [$i] = $row [$key];
				$i ++;
			}
			if (!isset($result)) {
				$result=array();
			}


		}else{
			$result=array();
		}

		return $result;
	}

	//whc
	function exc($sql) {
		return $this->query ( $sql );
	}

	//lock write
	function lockWrite($tableName){
		return $this->query ( "LOCK TABLES $tableName WRITE" );
	}
	//lock read
	function lockRead($tableName){
		return $this->query ( "LOCK TABLES $tableName READ" );
	}

    function lock($tableName){
		$w= $this->query ( "LOCK TABLES $tableName WRITE" );
		$r= $this->query ( "LOCK TABLES $tableName READ" );
		return ($w && $r)?true:false;
	}
	//unlock table
    function unlock(){
		return $this->query ( "UNLOCK TABLES" );
	}
	//whc
	function begin(){
		return $this->query('begin');
	}

   //whc
	function rollback(){
		return $this->query('rollback');
	}
  //whc
	function commit(){
		return $this->query('commit');
	}

	function close() {
		return mysql_close ( $this->link );
	}

	function halt($message = '', $sql = '') {
		//define('CACHE_FORBIDDEN', TRUE);
		die ( $message . $sql );
		//require_once 'db_mysql_error.inc.php';
	}


	function insert($table,$arr){
		if(is_array($arr)){
			$key='';
			$value='';
			foreach($arr as $k=>$v){
				$key.="`".$k."`,";
				$value.="'$v',";
			}
			$key=rtrim($key,',');
			$value=rtrim($value,',');
			$sql="insert into $table ($key) values ($value)";
			//echo $sql;
			return $this->exc($sql);
		}else{
			return false;
		}
	}

	function update($table,$arr,$whereArr){
	    if(is_array($whereArr)){
	    	$where="";
	    	foreach($whereArr as $kx=>$vx){
	    		$where.=" and `$kx`='{$vx}'";
	    	}
	    	$where=ltrim($where," and");
	    	$where=" where $where";
	    }else{
	    	$where=" where 1=1";
	    }
		if(is_array($arr)){
			$upStr="";
			foreach($arr as $k=>$v){
				$upStr.="`$k`='$v',";
			}
			$upStr=rtrim($upStr,',');
			$sql="update $table set $upStr $where";
			//echo $sql;
			return $this->exc($sql);
		}else{
			return false;
		}
	}
}

?>
